class Solution {
    public int[] relativeSortArray(int[] arr1, int[] arr2) {
        int[] hash = new int[1001];
        Arrays.fill(hash, 0);
        int index = -1;

        for (int i: arr1) {
            hash[i]++;
        }
        for (int i: arr2) {
            while (hash[i] > 0) {
                hash[i]--;
                arr1[++index] = i;
            }
        }
        for (int i = 0; i < 1001; i++) {
            while (hash[i] > 0) {
                hash[i]--;
                arr1[++index] = i;
            }
        }
        return arr1;
    }
}